﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using SkeinforgeWP8.Resources;
using System.Threading;
using System.Diagnostics;
using System.IO;
using System.Text;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using SharpCompress.Reader;
using System.ComponentModel;

namespace SkeinforgeWP8
{
    public partial class MainPage : PhoneApplicationPage
    {
        BoxStream bs = null;
        Thread sliceThread = null;

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            bs = new BoxStream(this);

            unzipSkein();

            // Sample code to localize the ApplicationBar
            //BuildLocalizedApplicationBar();
        }

        public void DispatchInvoke(Action a)
        {
            if (Dispatcher == null)
                a();
            else
                Dispatcher.BeginInvoke(a);
        }

        private void unzipSkein()
        {
            try
            {
                using (Stream stream = File.OpenRead("Skeinforge.zip"))
                {
                    var reader = ReaderFactory.Open(stream);
                    while (reader.MoveToNextEntry())
                    {
                        if (!reader.Entry.IsDirectory)
                        {
                            Stream writestream = File.Create(reader.Entry.FilePath);
                            reader.WriteEntryTo(writestream);
                            writestream.Close();
                        }
                        else
                        {
                            Directory.CreateDirectory(reader.Entry.FilePath);
                        }
                    }
                    reader.Dispose();
                    stream.Close();
                }

                using (Stream stream = File.OpenRead("PyLibs.zip"))
                {
                    var reader = ReaderFactory.Open(stream);
                    while (reader.MoveToNextEntry())
                    {
                        if (!reader.Entry.IsDirectory)
                        {
                            Stream writestream = File.Create(reader.Entry.FilePath);
                            reader.WriteEntryTo(writestream);
                            writestream.Close();
                        }
                        else
                        {
                            Directory.CreateDirectory(reader.Entry.FilePath);
                        }
                    }
                    reader.Dispose();
                    stream.Close();
                }

                using (Stream stream = File.OpenRead("skeintemp.zip"))
                {
                    var reader = ReaderFactory.Open(stream);
                    while (reader.MoveToNextEntry())
                    {
                        if (!reader.Entry.IsDirectory)
                        {
                            Stream writestream = File.Create(reader.Entry.FilePath);
                            reader.WriteEntryTo(writestream);
                            writestream.Close();
                        }
                        else
                        {
                            Directory.CreateDirectory(reader.Entry.FilePath);
                        }
                    }
                    reader.Dispose();
                    stream.Close();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

        private void slice()
        {
            try
            {
                DispatchInvoke(() =>
                {
                    OutBox.Text += "Starting skeinforge\n";
                });

                var ipy = Python.CreateEngine();
                var iscp = ipy.CreateScope();
                iscp.SetVariable("rootP", Directory.GetCurrentDirectory());
                ipy.ExecuteFile("Pathsetter.py", iscp);
                var ipath = ipy.GetSysModule().GetVariable("path");

                ScriptEngine m_engine = Python.CreateEngine();
                ScriptScope m_scope = m_engine.CreateScope();
                m_engine.GetSysModule().SetVariable("path", ipath);

                m_engine.Runtime.IO.SetOutput(bs, Encoding.UTF8);
                m_engine.Runtime.IO.SetErrorOutput(bs, Encoding.UTF8);

                m_engine.ExecuteFile(Directory.GetCurrentDirectory() + "\\Skeinforge\\skeinforge_application\\skeinforge_utilities\\skeinforge_craft.py", m_scope);

                string stl_path = Directory.GetCurrentDirectory() + "\\test.stl";
                object func = m_scope.GetVariable("makeGcode");
                object result = m_engine.Operations.Invoke(func, stl_path);
             
                DispatchInvoke(() =>
                {
                    Scroller.IsEnabled = true;
                    Scroller.ScrollToVerticalOffset(0);

                    OutBox.IsReadOnly = false;
                    OutBox.MaxLength = result.ToString().Length;
                    OutBox.Text = result.ToString();
                    OutBox.Height = Scroller.ScrollableHeight;
                    
                    Slice_Button.IsEnabled = true;

                    Debug.WriteLine("Scroll height: " + Scroller.ScrollableHeight);
                    Debug.WriteLine("Box max height: " + OutBox.MaxHeight);
                    Debug.WriteLine("Box height: " + OutBox.ActualHeight);
                });
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Py error: " + ex.Message);
            }
             
        }

        private void Slice_Button_Click(object sender, RoutedEventArgs e)
        {
            Slice_Button.IsEnabled = false;
            OutBox.IsReadOnly = true;
            Scroller.IsEnabled = false;
            OutBox.Text = "Slicing output:\n";
            sliceThread = new Thread(new ThreadStart(this.slice));
            sliceThread.Start();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            if (sliceThread != null)
                sliceThread.Abort();

            Slice_Button.IsEnabled = true;
        }

        // Sample code for building a localized ApplicationBar
        //private void BuildLocalizedApplicationBar()
        //{
        //    // Set the page's ApplicationBar to a new instance of ApplicationBar.
        //    ApplicationBar = new ApplicationBar();

        //    // Create a new button and set the text value to the localized string from AppResources.
        //    ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
        //    appBarButton.Text = AppResources.AppBarButtonText;
        //    ApplicationBar.Buttons.Add(appBarButton);

        //    // Create a new menu item with the localized string from AppResources.
        //    ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
        //    ApplicationBar.MenuItems.Add(appBarMenuItem);
        //}
    }
}